{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "initial_id",
   "metadata": {
    "collapsed": true,
    "ExecuteTime": {
     "end_time": "2023-11-13T16:09:16.202716400Z",
     "start_time": "2023-11-13T16:09:16.179676100Z"
    }
   },
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "import pandas as pd\n",
    "from pandas import DataFrame\n",
    "import glob\n",
    "import warnings\n",
    "\n",
    "warnings.filterwarnings(\"ignore\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "outputs": [],
   "source": [
    "def sortDictValue(dict, is_reverse):\n",
    "    \"\"\"\n",
    "    将字典按照value排序\n",
    "    :param dict: 待排序的字典\n",
    "    :param is_reverse: 是否按照倒序排序\n",
    "    :return s: list\n",
    "    \"\"\"\n",
    "    # 对字典的值进行倒序排序,items()将字典的每个键值对转化为一个元组,key输入的是函数,item[1]表示元组的第二个元素,reverse为真表示倒序\n",
    "    tups = sorted(dict.items(), key=lambda item: item[1], reverse=is_reverse)\n",
    "    # s = ''\n",
    "    s = []\n",
    "    for tup in tups:  # 合并成csv需要的逗号分隔格式\n",
    "        if tup[-1] > 1:  # 过滤小于1的值\n",
    "            # s = s + tup[0] + ',' + str(tup[1]) + '\\n'\n",
    "            if isinstance(tup[0],tuple):\n",
    "                s.append([*tup[0],tup[1]])\n",
    "            else:\n",
    "                s.append(tup)\n",
    "    return s\n",
    "\n",
    "\n",
    "def build_matrix(co_authors_list, is_reverse):\n",
    "    \"\"\"\n",
    "    根据共同列表,构建共现矩阵(存储到字典中),并将该字典按照权值排序\n",
    "    :param co_authors_list: 共同列表\n",
    "    :param is_reverse: 排序是否倒序\n",
    "    :return node_df: 三元组形式的节点 DataFrame\n",
    "    :return edge_df: 三元组形式的边  DataFrame\n",
    "    \"\"\"\n",
    "    node_dict = {}  # 节点字典,包含节点名+节点权值(频数)\n",
    "    edge_dict = {}  # 边字典,包含起点+目标点+边权值(频数)\n",
    "    # 第1层循环,遍历整表的每行信息\n",
    "    for row_authors in co_authors_list:\n",
    "        row_authors_list = row_authors  # 依据','分割每行,存储到列表中\n",
    "        # 第2层循环\n",
    "        for index, pre_au in enumerate(row_authors_list):  # 使用enumerate()以获取遍历次数index\n",
    "            # 统计单个词出现的频次\n",
    "            if pre_au not in node_dict:\n",
    "                node_dict[pre_au] = 1\n",
    "            else:\n",
    "                node_dict[pre_au] += 1\n",
    "            # 若遍历到倒数第一个元素,则无需记录关系,结束循环即可\n",
    "            if pre_au == row_authors_list[-1]:\n",
    "                break\n",
    "            connect_list = row_authors_list[index + 1:]\n",
    "            # 第3层循环,遍历当前行词后面所有的词,以统计两两词出现的频次\n",
    "            for next_au in connect_list:\n",
    "                A, B = pre_au, next_au\n",
    "                # 固定两两词的顺序\n",
    "                # 仅计算上半个矩阵\n",
    "                if A == B:\n",
    "                    continue\n",
    "                if A > B:\n",
    "                    A, B = B, A\n",
    "                key = (A , B)  # 格式化为逗号分隔A,B形式,作为字典的键\n",
    "                # 若该关系不在字典中,则初始化为1,表示词间的共同出现次数\n",
    "                if key not in edge_dict:\n",
    "                    edge_dict[key] = 1\n",
    "                else:\n",
    "                    edge_dict[key] += 1\n",
    "    # 对得到的字典按照value进行排序 并且转为df对象\n",
    "    node_df = DataFrame(sortDictValue(node_dict, is_reverse), columns=[\"Label\", \"Weight\"])  # 节点\n",
    "    edge_df = DataFrame(sortDictValue(edge_dict, is_reverse), columns=[\"Source\", \"Target\", \"Weight\"])  # 边\n",
    "    return node_df, edge_df\n",
    "\n",
    "\n",
    "def multipleDataFrameToExcel(node_df, edge_df, path):\n",
    "    # 创建一个 ExcelWriter 对象\n",
    "    with pd.ExcelWriter(f\"{path}.xlsx\", engine='xlsxwriter') as writer:\n",
    "        # 将每个 DataFrame 写入不同的工作表\n",
    "        node_df.to_excel(writer, sheet_name='node', index=False)\n",
    "        edge_df.to_excel(writer, sheet_name='edge', index=False)\n",
    "    print(f\"\\t共现矩阵 已保存到文件 {path}.xlsx\")\n"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2023-11-13T16:09:16.234224100Z",
     "start_time": "2023-11-13T16:09:16.217262300Z"
    }
   },
   "id": "3bb7bd806f8b1f82"
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "outputs": [],
   "source": [
    "def strToList(row):\n",
    "    row['职位'] = eval(row[\"职位\"])\n",
    "    row['任职要求'] = eval(row[\"任职要求\"])\n",
    "    return row"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2023-11-13T16:09:16.265224400Z",
     "start_time": "2023-11-13T16:09:16.234224100Z"
    }
   },
   "id": "cde30a152cf389b8"
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\t共现矩阵 已保存到文件 ../Data/共现矩阵/boss直聘_职位.xlsx\n",
      "\t共现矩阵 已保存到文件 ../Data/共现矩阵/boss直聘_任职要求.xlsx\n",
      "\t共现矩阵 已保存到文件 ../Data/共现矩阵/CareerBuilder_职位.xlsx\n",
      "\t共现矩阵 已保存到文件 ../Data/共现矩阵/CareerBuilder_任职要求.xlsx\n",
      "\t共现矩阵 已保存到文件 ../Data/共现矩阵/CIA_职位.xlsx\n",
      "\t共现矩阵 已保存到文件 ../Data/共现矩阵/CIA_任职要求.xlsx\n",
      "\t共现矩阵 已保存到文件 ../Data/共现矩阵/DNI_职位.xlsx\n",
      "\t共现矩阵 已保存到文件 ../Data/共现矩阵/DNI_任职要求.xlsx\n",
      "\t共现矩阵 已保存到文件 ../Data/共现矩阵/linkedin_职位.xlsx\n",
      "\t共现矩阵 已保存到文件 ../Data/共现矩阵/linkedin_任职要求.xlsx\n",
      "\t共现矩阵 已保存到文件 ../Data/共现矩阵/Simplyhired_职位.xlsx\n",
      "\t共现矩阵 已保存到文件 ../Data/共现矩阵/Simplyhired_任职要求.xlsx\n",
      "\t共现矩阵 已保存到文件 ../Data/共现矩阵/智联招聘_职位.xlsx\n",
      "\t共现矩阵 已保存到文件 ../Data/共现矩阵/智联招聘_任职要求.xlsx\n"
     ]
    }
   ],
   "source": [
    "files = glob.glob(\"../Data/语料库创建result/*\")\n",
    "\n",
    "path_ = \"../Data/共现矩阵/\"\n",
    "if not os.path.exists(path_):\n",
    "    os.mkdir(path_)\n",
    "\n",
    "for file in files:\n",
    "    file_name = file.replace('\\\\', '/').split('/')[-1].split('.')[0]\n",
    "    save_path = path_ + file_name\n",
    "    df = pd.read_excel(file)\n",
    "    # 删除重复行\n",
    "    df = df.drop_duplicates(keep='last')\n",
    "    # 去掉缺失值\n",
    "    df = df.dropna(subset=['职位', '任职要求'])\n",
    "    df.apply(func=strToList, axis=1)\n",
    "    nodeDf, edgeDf = build_matrix(df[\"职位\"], is_reverse=True)\n",
    "    multipleDataFrameToExcel(nodeDf,edgeDf,save_path+\"_职位\")\n",
    "    nodeDf, edgeDf = build_matrix(df[\"任职要求\"], is_reverse=True)\n",
    "    multipleDataFrameToExcel(nodeDf,edgeDf,save_path+\"_任职要求\")"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2023-11-13T16:09:35.123284600Z",
     "start_time": "2023-11-13T16:09:16.251223500Z"
    }
   },
   "id": "d12f1d0ee6f68144"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
